import box/{logger,condit,tools} x11/{yaml,stop} shell/termux

# 参数解析，注册
start_virgl_server=false
start_x11_app=true
start_xfce_desktop=true
reception_runtime=false

# 参数解析，检查
LONG=start-virgl-server,no-start-app,no-start-desktop,reception,help
OPTS=$(getopt --long "$LONG" -- "$@")
return=$?

# 参数解析，赋值
if ! ((return));then
  eval set -- "$OPTS"
  while true;do
  case "$1" in
    --start-virgl-server)
      start_virgl_server=true
      shift;;
    --no-start-app)
      start_x11_app=false
      shift;;
    --no-start-desktop)
      start_xfce_desktop=false
      shift;;
    --reception)
      reception_runtime=true
      shift;;
    --)
      shift
      break;;
    esac
  done
else
  Err "参数解析失败..."
  exit
fi

if ! Has-Process $(List-X11-All-Process-Id);then
  Warn "已有进程占用，请先关闭"
  exit
fi

pulseaudio -nDF $TTB_CONFIG/other/pulseaudio_config.pa &>/dev/null

export LANG=zh_CN.UTF-8
export PULSE_SERVER=tcp:127.0.0.1:4713

# 启动 GL 服务器（用于 Proot 容器 GPU 硬件加速）
if In-Value start_virgl_server;then
  virgl_test_server_android &>/dev/null &
  pid=$!
  Set-X11-Process-Id virglpid pid
  Info "启动 virgl 服务器，进程号 $pid"
fi

# 打开 Termux:X11（如果有的话）
if Has-Termux-Plugin x11;then

  termux-x11 &>/dev/null &
  pid=$!
  Set-X11-Process-Id x11pid pid
  Info "启动 termux-x11 服务，进程号 $pid"
  sleep 1
  
  if In-Value start_x11_app;then
    am start \
    com.termux.x11/com.termux.x11.MainActivity \
    &>/dev/null
  fi

  display="DISPLAY=:0 dbus-launch --exit-with-session startxfce4"
  if In-Value reception_runtime;then
    trap Stop-X11-Process 2
    Info "前台运行中，按 Ctrl - C 终止..."
    eval "$display"
  else
    if In-Value start_xfce_desktop;then
      eval "$display &>/dev/null &"
      pid=$!
      Set-X11-Process-Id display pid
      Info "启动 xfce4 桌面环境，进程号 $pid"
    fi
  fi
  
else
  Err "未安装Termux:X11的Android应用"
fi